package com.wsd.bookkeeping.controller;

import com.wsd.bookkeeping.entity.AccountUser;
import com.wsd.bookkeeping.form.PermissionForm;
import com.wsd.bookkeeping.form.TransferForm;
import com.wsd.bookkeeping.service.AccountService;
import com.wsd.bookkeeping.service.RightService;
import com.wsd.bookkeeping.service.UserService;
import com.wsd.bookkeeping.vo.UserRightListVO;
import com.wsd.common.entity.ResponseEntity;
import com.wsd.common.utils.DateUtils;
import com.wsd.common.utils.ResponseUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RightService rightService;
    @Resource
    private UserService userService;
    @Resource
    private AccountService accountService;

    @PostMapping("/invite")
    public ResponseEntity saveInvite(AccountUser accountUser) {
        accountUser.setParticipantDate(DateUtils.currentDateNString());

        return null;
    }

    @DeleteMapping("/book/{id}")
    public ResponseEntity deleteBookUser(@PathVariable Integer id) {
        return ResponseUtils.ret(userService.removeBookUser(id));
    }

    /**
     * 获取用户权限列表
     * @param form
     */
    @PutMapping("/permission")
    public ResponseEntity saveOrUpdateUserPermission(@RequestBody PermissionForm form) {
        return ResponseUtils.ret(rightService.saveOrUpdateUserPermission(form));
    }

    /**
     * 移交管理员权限
     */
    @PutMapping("/transfer")
    public ResponseEntity transferAuthority(@RequestBody TransferForm form) {
        return ResponseUtils.ret(accountService.transferAuthority(form));
    }

    /**
     * 获取权限列表
     */
    @GetMapping("/rights")
    public ResponseEntity getRightList() {
        return ResponseEntity.success().put("rights", rightService.getRightList());
    }

    /**
     * 获取用户在该账本的权限
     * @param bookId 账本Id
     * @param userId 人员Id
     */
    @GetMapping("/{userId}/{bookId}/right")
    public ResponseEntity getRightListByUserId(@PathVariable Integer userId, @PathVariable Integer bookId) {
        UserRightListVO userRightList = rightService.getRightListById(userId, bookId);
        List<Integer> rightIdList = null;
        if (Objects.isNull(userRightList)) {
            rightIdList = new ArrayList<>();
        } else {
            rightIdList = userRightList.getRightList();
        }
        return ResponseEntity.success().put("right", rightIdList);
    }

    /**
     * 账本用户页面，用户详细信息
     * @param bookId 账本Id
     * @param userId 人员Id
     */
    @GetMapping("/info/{userId}/{bookId}")
    public ResponseEntity getUserInfoByBookId(@PathVariable Integer bookId, @PathVariable Integer userId) throws InterruptedException {
        return ResponseEntity.success().put("info", rightService.getUserInfo(userId, bookId));
    }
}
